package code.tools.other
{
	import flash.display.Stage;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	/**
	 *秒计时器 
	 * @author Yuri
	 * 
	 */
	public class SecondDrive
	{
		private static var _stage:Stage;
		private static var timer:Timer;
		
		private static var listenerDic:Dictionary;
		private static var pauseDic:Dictionary;
		
		public static function get stage():Stage
		{
			return _stage;
		}
		
		public static function set stage(value:Stage):void
		{
			_stage = value;
			timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER, stageEnterFrame);
			currentTimer = getTimer();
			timer.start();
		}
		
		private static var _index:int = 0;
		private static var currentTimer:int;
		private static var _errorrange:int; 
		private static function stageEnterFrame(e:TimerEvent):void
		{
			_errorrange += getTimer() - currentTimer - 1000;
			currentTimer = getTimer();
			if(_errorrange>=1000) {
				_errorrange -=1000;
				excute(e);
			}
			excute(e);
		}
		
		private static function excute(e:TimerEvent):void{
			if(listenerDic){
				for each(var fn:Function in listenerDic){
					if(pauseDic && pauseDic[fn]) continue;
					fn();
					e.updateAfterEvent();
				}
			}
			_index++;
		}
		
		public static function addEventListener(fn:Function,interval:int = 1000):void
		{
			if(fn==null) return;
			if (!listenerDic)
			{
				listenerDic = new Dictionary();
			}
			listenerDic[fn] = fn;
		}
		
		
		public static function removeListener(fn:Function):void
		{
			if (listenerDic && listenerDic[fn])
			{
				delete listenerDic[fn]; // or set null?
				if(pauseDic && pauseDic[fn])  delete pauseDic[fn];
			}
		}
		
		public static function hasEventListener(fn:Function):Boolean{
			if (listenerDic && listenerDic[fn])
			{
				return true;
			}
			return false;
		}
		
		/**
		 *暂停单个函数
		 */
		public static function pause(fn:Function = null):void {
			if(fn!=null){
				if(hasEventListener(fn)){
					if(!pauseDic) pauseDic = new Dictionary();
					pauseDic[fn] = 1;
				}
			}else{
				pauseAll();
			}
		}
		
		/**
		 *播放单个函数 
		 */
		public static function play(fn:Function = null):void {
			if(fn!=null){
				if(pauseDic && pauseDic[fn]) delete pauseDic[fn];
			}else{
				playAll();
			}
			
		}
		/**
		 * 暂停所有函数
		 */
		private static function pauseAll():void {
			if(timer) timer.stop();
		}
		/**
		 * 播放所有函数
		 */
		private static function playAll():void {
			pauseDic = null;
			if(timer) timer.start();
		}
	}
}